import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  permissions: [],
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 设置用户权限
  SET_PERMISSIONS: (state, permissions) => {
    state.introduction = permissions
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 用户登陆
  login({ commit }, userInfo) {
    // 登录时从参数中取出用户名和密码
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // 请求src/api/user.js里面的login方法并传入参数
      login({ username: username.trim(), password: password }).then(response => {
        const { token } = response
        // 登录成功后设置token到vuex
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        // 获取响应的用户信息
        const { permissions, roles, picture, username } = response
        if (!username) {
          // 如果用户名不存在 重新登录
          reject('请登录')
        }
        commit('SET_ROLES', roles)// 用户角色
        commit('SET_NAME', username)// 用户名
        commit('SET_AVATAR', picture)// 用户头像
        commit('SET_PERMISSIONS', permissions)// 用户权限
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        // 清空token
        commit('SET_TOKEN', '')
        // 清空角色
        commit('SET_ROLES', [])
        // 清空权限
        commit('SET_PERMISSSIONS', [])
        removeToken()
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // 清空token
      commit('SET_TOKEN', '')
      // 清空角色
      commit('SET_ROLES', [])
      // 清空权限
      commit('SET_PERMISSSIONS', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
